using System;
using System.Collections.ObjectModel;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using Castle.Core.Logging;

namespace DreamDriven.Wcf
{
    public class LogExceptionHandler : IServiceBehavior, IErrorHandler
    {
        private ILogger _logger = NullLogger.Instance;
        
        public ILogger Logger
        {
            get { return _logger; }
            set { _logger = value; }
        }

        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {            
        }

        
        public bool HandleError(Exception error)
        {
            Logger.Error("Unhandled exception occurred", error);
            return false;
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {            
        }

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {            
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
            {
                dispatcher.ErrorHandlers.Add(this);
            }
        }
    }
}